package com.bluesimon.wbf.usercenter;

import com.bluesimon.wbf.IUser;
import com.bluesimon.wbf.Logined;
import com.bluesimon.wbf.Response;
import com.bluesimon.wbf.utils.MD5Util;
import com.bluesimon.wbf.utils.Uploader;
import org.ume.school.modules.model.ErrorTag;
import org.ume.school.modules.model.HeadDefEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Django on 2017/7/15.
 */
@RestController
@RequestMapping("/v0.1/user")
public class UserCenterController {

    @Resource
    private UserService userService;

    /**
     * 快速注册
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Response<User> register(@RequestParam("email") String email,
                                   @RequestParam("username") String username,
                                   @RequestParam("pass") String password,
                                   @RequestParam(value = "redirect", required = false) String redirect,
                                   HttpServletRequest request,
                                   RedirectAttributes attr) {
        User user = new User();
        user.setUserName(email);
        user.setPassword(MD5Util.getMD5(password));
        user.setEmail(email);
        user.setNickName(username);
        Response resp = new Response<>();
        if (StringUtils.isEmpty(user.getUserName())) {
            resp.setCode(ErrorTag.NOT_ALLOW_USERNAME_EMPTY.getCode());
            resp.setMessage(ErrorTag.NOT_ALLOW_USERNAME_EMPTY.getMessage());
        } else {
            User temp = userService.getUserByName(user.getUserName());
            if (null != temp) {
                resp.setCode(ErrorTag.REPEAT_USER_NAME.getCode());
                resp.setMessage(ErrorTag.REPEAT_USER_NAME.getMessage());
            } else {
                if (StringUtils.isEmpty(user.getNickName())) {
                    user.setNickName(HeadDefEnum.getRandom()[0]);
                }
                if (StringUtils.isEmpty(user.getHeadImage())) {
                    user.setHeadImage(HeadDefEnum.getRandom()[1]);
                }
                user.setLastModified(new Date());
                User u = userService.register(user);
                if (u != null) {
                    resp.setData(u);
                    request.getSession().setAttribute(IUser.LOGIN_USER, u);
                } else {
                    resp.setCode(ErrorTag.LOGIN_FAILURE.getCode());
                    resp.setMessage(ErrorTag.LOGIN_FAILURE.getMessage());
                }
            }
        }
        return resp;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Response<User> login(@RequestParam("email") String loginName,
                                @RequestParam("pass") String password,
                                @RequestParam(value = "redirect", required = false) String redirect,
                                HttpServletRequest request,
                                RedirectAttributes attr) {
        Response resp = new Response<>();
        User u = userService.login(loginName, MD5Util.getMD5(password));
        if (u != null) {
            resp.setData(u);
            request.getSession().setAttribute(IUser.LOGIN_USER, u);
        } else {
            resp.setCode(ErrorTag.LOGIN_FAILURE.getCode());
            resp.setMessage(ErrorTag.LOGIN_FAILURE.getMessage());
        }
        return resp;
    }

    @RequestMapping(value = "/logout")
    public ModelAndView logout(HttpServletRequest request) {
        request.getSession().removeAttribute(IUser.LOGIN_USER);
        ModelAndView mModelAndView = new ModelAndView("redirect:/");
        return mModelAndView;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Response<User> getUser(@PathVariable("id") String id) {
        Response<User> resp = new Response<>();
        User u = userService.getUser(id);
        if (u == null) {
            resp.setCode(ErrorTag.NOT_FIND_USER.getCode());
            resp.setCode(ErrorTag.NOT_FIND_USER.getMessage());
        } else {
            resp.setData(u);
        }
        return resp;
    }

    /**
     * 修改基本信息 , 除了头像与密码
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/info", method = RequestMethod.POST)
    public Response<User> modifyUserInfo(@PathVariable("id") String id, @RequestBody User user,HttpServletRequest request) {
        Response<User> resp = new Response<>();
        User u = userService.getUser(id);
        if (u == null) {
            resp.setCode(ErrorTag.NOT_FIND_USER.getCode());
            resp.setCode(ErrorTag.NOT_FIND_USER.getMessage());
        } else {
            //设置修改属性
            u.setNickName(user.getNickName());
            u.setEmail(user.getEmail());
            u.setAddr(user.getAddr());
            u.setCity(user.getCity());
            u.setSex(user.getSex());
            u.setSummary(user.getSummary());
            u = userService.update(u);
            request.getSession().setAttribute(IUser.LOGIN_USER, u);
            resp.setData(u);
        }
        return resp;
    }

    /**
     * 修改头像
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/head", method = RequestMethod.POST)
    public Response<User> modifyUserHead(@PathVariable("id") String id, @RequestParam("head_image") String headImage,HttpServletRequest request) {
        Response<User> resp = new Response<>();
        User u = userService.getUser(id);
        if (u == null) {
            resp.setCode(ErrorTag.NOT_FIND_USER.getCode());
            resp.setCode(ErrorTag.NOT_FIND_USER.getMessage());
        } else {
            u.setHeadImage(headImage);
            u = userService.update(u);
            request.getSession().setAttribute(IUser.LOGIN_USER, u);
            resp.setData(u);
        }
        return resp;
    }

    /**
     * 修改密码
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/pw", method = RequestMethod.POST)
    public Response<User> modifyUserPassword(@PathVariable("id") String id, @RequestParam("password") String password) {
        Response<User> resp = new Response<>();
        User u = userService.getUser(id);
        if (u == null) {
            resp.setCode(ErrorTag.NOT_FIND_USER.getCode());
            resp.setCode(ErrorTag.NOT_FIND_USER.getMessage());
        } else {
            u.setPassword(MD5Util.getMD5(password));
            u = userService.update(u);
            resp.setData(u);
        }
        return resp;
    }


    /**
     * 验证是否登录, 可作为心跳请求。
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/valid_login", method = RequestMethod.GET)
    public Response<IUser> vaild(@Logined IUser user) {
        if (null != user) {
            return new Response<>(user);
        } else {
            return new Response<>(null);
        }
    }

    /**
     * 初始化账号
     *
     * @return
     */
    @RequestMapping(value = "/init_admin", method = RequestMethod.GET)
    public void initAdmin() {
        User user = new User();
        user.setNickName("超级管理员");
        user.setUserName("admin");
        //两次MD5，一次是传输前，一次是传输后
        user.setPassword(MD5Util.getMD5(MD5Util.getMD5("123456")));
        user.setType(1);
        userService.register(user);
    }
}
